<script setup>
import {onMounted, h} from 'vue'
import {
  NAvatar,
  NButton,
  NFlex,
  NForm,
  NFormItem,
  NImage,
  NInput, NLayout, NLayoutContent,
  NSelect, NSwitch,
  NTabPane,
  NTabs,
  NTag,
  useMessage
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import api from '@/api'
import default_image from "@/assets/images/mz.jpg";
import {getToken, renderIcon} from "@/utils";
import TheIcon from "@/components/icon/TheIcon.vue";
import {useCRUD} from "@/composables";
import CrudModal from "@/components/table/CrudModal.vue";

const base_path = import.meta.env.VITE_BASE
const message = useMessage()
const {
  modalVisible,
  modalAction,
  modalTitle,
  modalLoading,
  handleAdd,
  handleDelete,
  handleEdit,
  handleSave,
  modalForm,
  modalFormRef,
} = useCRUD({
  name: '病例',
  initForm: {},
  doCreate: api.createOrder,
  doDelete: api.deleteOrder,
  doUpdate: api.updateOrder,
  refresh: () => on_ref(),
})

const props = defineProps({
  infoData: {
    type: Object,
    required: true
  }
});
const data = reactive({
  orders: [],
  card_loading: false,
  select_customer: {
    name: "未选择",
    card_number: "--",
    user_level_name: "--",
    mobile: "--",
    bi_date: "--",
    sex: "--",
    hkqd: "--",
    age: "--",
    created_at: "--",
    last_come: "--",
    record_hobby: [],
    totals: {
      weimei: 0,
      cdp: 0,
      fujia: 0,
      other: 0,
      buy_money: 0,
      cases: 0,
      appoint_count: 0,
      return_count: 0,
      operation_count: 0,
      face_count: 0,
      test_count: 0,
      having_customers: 0,
      customers_level5: 0

    }
  },
  tab_goods: [],
  meeting_users: [],
  config: [],
  uploadAction: base_path + '/system/base/userimg',
  token: getToken(),
  pay: false,
  pay_data: [],
  payForm: {
    id: 0,
    order_id: 0,
    pay_type: 3,
    images: [],
    images_pc: []
  },
  get_jf_data: [],
  fjq: [],
  keyword: "",
  up_photo: false,
  PhotoForm: {
    id: 0,
    before_images: [],
    after_images: []
  },
  show_add: false,
  materialForm: {
    case_id:0,
    children:[]
  },
  materialtemp:[],
  durgs:[]
});

onMounted(() => {
  data.select_customer = props.infoData
  on_ref()
})


function on_ref() {
  get_order_list()
}

function get_order_list() {
  data.card_loading = true
  api.getCases({
    user_id: data.select_customer.user_id,
    keyword: data.keyword
  }).then((res) => {
    data.orders = res.data.items
    data.card_loading = false
    data.loading = false
  })
}


function search_order() {
  data.loading = true
  get_order_list()
}


function on_add(item) {
  let projects = item.projects
  let project_ids = projects.map(item => item.project_id).join(',');

  if(data.durgs.length===0){
    api.getDrugsAll().then((res) => (data.durgs = res.data))
  }

  data.show_add = true
  api.getMaterialTemp({
    id:project_ids
  }).then((res) => {
    data.materialtemp = res.data
    data.materialForm.case_id = item.id
    data.materialForm.children = data.materialtemp
  })
}

function save_material() {
  api.createMaterial(data.materialForm).then((res) => {
    message.success('耗材上传成功')
    data.show_add = false
    on_ref()
  })
}

const onCreate = () => {
  return {
    drug_id: null,
    drug_range:'',
    number:null,
    is_for_self:1

  }
}

</script>
<template>
  <div class="container" style="height: calc(100vh - 106px);">
    <div class="search">
      <NInput size="large" @change="search_order" v-model:value="data.keyword" :loading="data.loading" clearable
              type="text" placeholder="请输入卡项,项目名称检索"/>
    </div>
    <n-spin :show="data.card_loading" style="--n-opacity-spinning:0.1;height: calc(100vh - 225px);">
      <n-scrollbar v-if="data.orders.length>0" style="max-height: calc(100vh - 180px);padding:0 20px 20px 0px">
        <n-collapse class="cards" accordion :default-expanded-names="[data.orders[0].id]">
          <n-collapse-item :name="item.id" v-for="item in data.orders" class="card" :disabled="!item.material_list">
            <template #header>
              <div style="display: flex; align-items: center;justify-content: flex-start">
                <n-h6 prefix="bar" type="info" style="margin: 0;font-size: 16px">
                  <div style="display: flex">
                    <n-button type="info" dashed size="large">病例单号:{{ item.id }}</n-button>
                    <div style="height:40px;line-height:20px;margin-left: 10px">
                <span v-for="item2 in item.projects" style="margin-right: 5px">
                  {{ item2.title }}<span style="font-size: 12px">X{{ item2.num }}</span>
                </span>
                      <br>
                      <span style="font-size: 12px;color:#747586">操作于:{{ item.created_at }}</span>
                    </div>
                  </div>
                </n-h6>
              </div>
            </template>
            <template #header-extra>
              <n-button type="primary" @click="on_add(item)" v-if="item.material_status_name==='未添加耗材'">添加
              </n-button>
              <n-button type="primary" dashed v-else disabled>{{ item.material_status_name }}</n-button>
            </template>

            <div class="project_list">

              <n-card size="small" :bordered="false" hoverable content-style="padding: 0px;"
                      :segmented="{content: true,footer: 'soft',}">
                <template #header>
                  <n-h6 prefix="bar" style="margin: 0;font-size: 14px">耗材明细</n-h6>
                </template>
                <template #footer>
                  <n-scrollbar x-scrollable>
                    <div class="tags-container">
                      <n-card v-for="item2 in item.material_list.children" style="width: 300px" size="small"
                               :segmented="{content: true,footer: 'soft',}">
                        <n-badge v-for="item3 in item2" :value="'x'+item3.total_number" :show="1"
                                 style="margin-right: 15px">
                          <n-tag :bordered="false" type="error">
                            {{ item3.drug_name }}
                            <span v-if="item3.is_for_self===0">[自购]</span>
                          </n-tag>
                        </n-badge>
                      </n-card>
                    </div>
                  </n-scrollbar>
                </template>
              </n-card>


            </div>

          </n-collapse-item>
        </n-collapse>
      </n-scrollbar>
      <n-empty v-else description="暂无数据" style="margin: 50px"></n-empty>
    </n-spin>

  </div>

  <n-drawer v-model:show="data.show_add" width="1000px">
    <n-drawer-content title="耗材添加" closable>
      <NForm
          ref="modalFormRef"
          label-placement="left"
          label-align="left"
          :label-width="80"
          :model="modalForm"
      >



          <n-card style="width: 100%;margin-bottom: 20px"  embedded v-for="item in data.materialtemp" size="small" content-style="padding: 10px;" :bordered="false" :segmented="{content: true,footer: 'soft',}">
                  <template #header>
                    <n-h6 prefix="bar" style="margin: 0;font-size: 18px">{{item.title}}</n-h6>
                  </template>
                  <n-layout  >
                        <n-layout-header  style="background: #fafafc">
                          <n-flex >
                            <n-tag size="large" style="width: 500px"> 选择耗材 </n-tag>
                            <n-tag size="large" style="width: 100px"> 建议数量 </n-tag>
                            <n-tag size="large" style="width: 100px"> 实际数量 </n-tag>
                            <n-tag size="large" style="width: 70px"> 是否出库 </n-tag>
                          </n-flex>
                        </n-layout-header>
                        <n-layout-content content-style="padding: 10px 0;"  style="background: #fafafc">
                          <n-dynamic-input v-model:value="item.content" :on-create="onCreate">
                            <template #default="{ value , index}">
                              <n-flex justify="space-between">

                                <n-cascader 
                                  style="width: 500px;"
                                  v-model:value="value.drug_id"
                                  clearable
                                  placeholder="请选择药品"
                                  :options="data.durgs"
                                  cascade
                                  check-strategy="children"
                                  show-path
                                  filterable
                                  clear-filter-after-select
                                  label-field="name"
                                  value-field="id"
                                  :ellipsis-tag-popover-props="{
                                    trigger: 'hover',
                                    placement: 'top'
                                  }"
                                />
                                <n-input disabled placeholder="无" v-model:value="value.drug_range" style="width: 100px"/>
                                <n-input-number min="0" placeholder="请输入次数" v-model:value="value.number" style="width: 100px"/>
                                <NSwitch
                                  v-model:value="value.is_for_self"
                                  :checked-value="1"
                                  :unchecked-value="0"
                                  :default-value="1"
                                  size="large"
                                  style="width: 70px"
                                />
                              </n-flex>
                            </template>
                          </n-dynamic-input>
                        </n-layout-content>
                      </n-layout>
          </n-card>


      </NForm>
      <template #footer>
        <n-button type="primary" style="margin-right: 0px" @click="save_material">
          <TheIcon icon="material-symbols:save-sharp" :size="16" class="mr-5"/>
          保存
        </n-button>
      </template>

    </n-drawer-content>


  </n-drawer>

</template>


<style>
.container {
  padding: 10px;
  //transform: translate(0);
  position: relative;
  height: 100%;

  .search {
    margin-bottom: 10px;
  }
}

.cards {
  margin: 0px;
}

.project {
  margin-bottom: 10px;
}

.project_list {
  background: #f3f3f3;
  padding: 20px;
  border-radius: 5px;

}

.add_cases {
  height: 60px;
  position: absolute;
  bottom: 0;
  background: #eee;
  width: 100%;
  padding: 10px;
  border-top-left-radius: 5px;
}

/* 修改滾輪滾動行為為橫軸 */
.n-scrollbar {
  overflow-y: hidden;
  overflow-x: auto;
}

.n-scrollbar .n-scrollbar-content {
  overflow-y: hidden;
  overflow-x: auto;
}

/* 確保橫向滾動容器 */
.tags-container {
  display: flex;
  flex-direction: row;
  white-space: nowrap;
}

</style>